//全局变量  
const tableEle = document.querySelector('table')
let stateAll = false // 全选框
/**
 *  1. 显示商品列表
 *      => 1.动态渲染localStorage中持久化存储的商品列表数据
 *         2.调用设置总价
 */
function showProductList() {
	let listStr = localStorage.getItem('CART-LIST') || '[]'
	list = JSON.parse(listStr)
	let str = `<tr>
                <th><input type= "checkbox" name="checkall"	${stateAll ? 'checked' : ''}></th>
                <th>序列号</th>
                <th>商品图片</th>
                <th>商品信息</th>
                <th>单价</th>
                <th>数量</th>
                <th width="100px">总价</th>
                <th>操作</th>
            </tr>`

	if (list[0]) {
		let arr = list.map(item => {
			return `<tr>
                 <td><input type= "checkbox" name="checkSingle" data-id="${item.id}" ${item.state ? 'checked' : ''}></td>
                 <td>${item.id}</td>
                 <td><img src="${item.url}" alt="pic1"/></td>
                 <td>${item.name}</td>
                 <td>${item.price}</td>
                 <td><input type="button" value="-" name="minus"  ${item.num == 0 ? 'disabled' : ''}    data-id="${
                    item.id
                }"/><input type="text" value="${item.num}" name="amount"/><input
                                    type="button"
                                    value="+"
                                    name="plus"
                                    data-id="${item.id}"
                                /></td>
                 <td>${(item.num * item.price).toFixed(2)}</td>
                 <td>移入收藏<br /><a href="javascript:void(0)" class="del" data-id="${item.id}">删除</a></td>
            </tr>`
		})
		tableEle.innerHTML = str + arr.join('') + `<a class="goA" href="./index.html"> > 继续购物</a>` + `<div class="clearAll">清空购物车</div>`
	} else {
		tableEle.innerHTML = str + `<h2>购物车空空的哦~，去看看心仪的商品吧~</h2>` + `<br>` +
			`<a class="goA" href="./index.html"> > 去购物</a>`
	}
	setTotalPrice()
	clearAll()
}
showProductList()

/**
 *  2. 加减删除
 *      => 1.加减删除localStorage中持久化存储的商品列表数据
 *         2.点击加减删调用显示商品列表    （貌似可优化）
 */
function bindDeleteProduct() {
	tableEle.addEventListener('click', function (e) {
		e = e || window.event
		let target = e.target || e.srcElement
		// 删除操作         localStorage本地存储
		if (target.getAttribute('class') == 'del') {
			if (!confirm('确定要删除该记录')) {
				return
			}
			let listStr = localStorage.getItem('CART-LIST') || '[]'
			list = JSON.parse(listStr)
			let id = target.dataset.id
			let index = list.findIndex(item => item.id == id)
			list.splice(index, 1)
			localStorage.setItem("CART-LIST", JSON.stringify(list))
			showProductList()
		}
		// 加操作           localStorage本地存储
		if (target.getAttribute('name') == 'plus') {
			let listStr = localStorage.getItem('CART-LIST') || '[]'
			list = JSON.parse(listStr)
			let id = target.dataset.id
			let product = list.find(item => item.id == id)
			product.num++
			localStorage.setItem("CART-LIST", JSON.stringify(list))
			showProductList()
		}
		// 减操作           localStorage本地存储
		if (target.getAttribute('name') == 'minus') {
			let listStr = localStorage.getItem('CART-LIST') || '[]'
			list = JSON.parse(listStr)
			let id = target.dataset.id
			let product = list.find(item => item.id == id)
			product.num--
			localStorage.setItem("CART-LIST", JSON.stringify(list))
			showProductList()
		}



		/* 
			全选操作        localStorage本地存储
				2.0操作数据
					1. 设置全选状态stateAll = !stateAll
					2. 设置所有复选框操作
		 */
		if (target.getAttribute("name") == "checkall") {
			let listStr = localStorage.getItem('CART-LIST') || '[]'
			list = JSON.parse(listStr)
			stateAll = !stateAll
			list.forEach(product => {
				product.state = stateAll
			})
			localStorage.setItem("CART-LIST", JSON.stringify(list))
			showProductList()
		}
		/* 
			单选操作        localStorage本地存储
				1. 设置当前选中商品状态state = !state
				2. 设置全选状态 stateAll
					if 所有单选中 则 全选中 否则 flase
		*/
		if (target.getAttribute("name") == "checkSingle") {
			let listStr = localStorage.getItem('CART-LIST') || '[]'
			list = JSON.parse(listStr)
			let id = target.dataset.id
			let product = list.find(item => item.id == id)
			product.state = !product.state
			stateAll = list.every(item => item.state == true)
			localStorage.setItem("CART-LIST", JSON.stringify(list))
			showProductList()
		}
	})
}
bindDeleteProduct()

/**
 * 1.计算所有商品总价
 * 2.设置总价
 */
function setTotalPrice() {
	const totalPriceEle = document.querySelector('.total-price')
	totalPriceEle.innerHTML = list.reduce((pr, cr) => (pr = pr + (cr.state ? cr.price * cr.num : 0)), 0).toFixed(2)
}
setTotalPrice()

/**
 * 右侧功能列表
 * 	=>底部滑动牵扯运动函数没有做完整版
 */
function rightBtnList() {
	const btnList = document.querySelectorAll(".right-fixed>div")
	btnList[0].addEventListener("click", function () {
		let s1
		if (s1) {
			clearInterval(s1)
		}
		s1 = setInterval(() => {
			document.documentElement.scrollTop -= 50
			if (document.documentElement.scrollTop == 0) {
				clearInterval(s1)
			}
		}, 50);
	})
	btnList[1].addEventListener("click", function () {

	})
	btnList[2].addEventListener("click", function () {

	})
	btnList[3].addEventListener("click", function () {

	})
	btnList[4].addEventListener("click", function () {
		document.documentElement.scrollTop = 6000
		// let s2
		// if(s2){
		//     clearInterval(s2)
		// }
		// s2 = setInterval(() => {
		//     document.documentElement.scrollTop +=50
		//     console.log(document.documentElement.scrollTop);
		//     if(document.documentElement.scrollTop >= 5000){
		//         clearInterval(s1)
		//     }
		// }, 50);
	})
}
rightBtnList()

/* 清空购物车 */
function clearAll() {
	const clearAllBtn = document.querySelector(".clearAll")
	clearAllBtn.addEventListener("click", function () {
		// 清空操作           localStorage本地存储
		if (!confirm('确定要清空购物车吗')) {
			return
		}
		let listStr = localStorage.getItem('CART-LIST') || '[]'
		list = JSON.parse(listStr)
		list = []
		localStorage.setItem("CART-LIST", JSON.stringify(list))
		showProductList()
	})
}